package com.yx.cloud.activity;

import android.animation.Animator;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.iot.product.sweeper.config.SweeperProductConfig;
import com.iot.sweeper.AppContext;
import com.iot.sweeper.param.CleanSettingParam;
import com.yx.cloud.R;
import com.yx.cloud.base.BaseActivity;
import com.yx.cloud.databinding.DustcollectingbarrelActivityBinding;
import com.yx.cloud.product.ProductConfigConstants;
import com.yx.cloud.utils.DisplayUtil;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.LoadProgressDialog;
import com.yx.cloud.utils.RomUtils;
import com.iot.product.sweeper.bean.CleanSettings;
import com.iot.product.sweeper.bean.Robot;
import com.iot.product.sweeper.bean.RobotStatus;
import com.iot.common.utils.Event;
import com.iot.common.utils.LogUtils;

import org.greenrobot.eventbus.EventBus;import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

/**
 * 集尘桶
 */
public class DustCollectingBarrelActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "DustCollectingBarrelActivity";
    private LoadProgressDialog loadProgressDialog;
    private Dialog dialog;
    private DustcollectingbarrelActivityBinding binding;
    private Robot robot;
    private CleanSettings settings;
    private JSONObject productConfig;
    private int frequency = -1;
    private String deviceType;

    @Override
    public void onCreate() {
        binding = DustcollectingbarrelActivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initData();
    }

    private void initData() {
        if (loadProgressDialog == null) {
            loadProgressDialog = new LoadProgressDialog(DustCollectingBarrelActivity.this);
        }
        //判断自动集尘是否打开
        robot = AppContext.get().getCurrentDevice();
        if (robot != null) {
            productConfig = AppContext.getConfig();
            DisplayUtil.show(binding.llDustCollectionSettings, productConfig.optBoolean(ProductConfigConstants.carpetSetting_suction));//集尘频率布局
            DisplayUtil.show(binding.llDustSuction, productConfig.optBoolean(ProductConfigConstants.dustSuction_time));//集尘吸力/集尘时长
            DisplayUtil.show(binding.llDustTime, productConfig.optBoolean(ProductConfigConstants.dustSuction_time));//集尘吸力/集尘时长

            settings = robot.getCleanSettings();
            String autoDust = settings.getAutoDust();
            LogUtils.i("集尘 ： " + autoDust);
            deviceType = productConfig.optString(ProductConfigConstants.productName);
            if ("ZW2X".equals(deviceType)) {
                if (autoDust.equals("0")) {
                    binding.dustSwitch.setChecked(false);
                    binding.llDustCollectionSettings.setVisibility(View.GONE);
                } else {
                    binding.dustSwitch.setChecked(true);
                    binding.llDustCollectionSettings.setVisibility(View.VISIBLE);
                    if (autoDust.equals("1")) {
                        setDustCollectionFrequencySettings("1");
                    } else if (autoDust.equals("2")) {
                        setDustCollectionFrequencySettings("2");
                    } else if (autoDust.equals("3")) {
                        setDustCollectionFrequencySettings("3");
                    }
                }
            } else {
                if (autoDust.equals("1")) {
                    binding.dustSwitch.setChecked(true);
                } else {
                    binding.dustSwitch.setChecked(false);
                }
            }

            int workState = robot.getRobotStatus().getWorkState();
            if (workState != RobotStatus.STATE_CHARGING) {
                binding.tvRobotIsNotCharging.setVisibility(View.VISIBLE);
                binding.btnDustImmediately.setEnabled(false);
            } else {
                binding.tvRobotIsNotCharging.setVisibility(View.GONE);
                binding.btnDustImmediately.setEnabled(true);
            }

        }
//        //判断当前集尘桶的状态
//        judgeDustState();
        //0关 1开
        binding.dustSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @SuppressLint("LongLogTag")
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (!buttonView.isPressed()) {
                    return;
                }
                Log.i(TAG, " isChecked ---------- " + isChecked);
                if (isChecked) {
                    //徐老师说打开时默认发1次
                    if ("ZW2X".equals(deviceType)) {
                        binding.llDustCollectionSettings.setVisibility(View.VISIBLE);
                    }
                    AppContext.getProductService().setDeviceCleanSettings(CleanSettingParam.newBuilder().autoDustFrequency(1).build());
                } else {
                    if ("ZW2X".equals(deviceType)) {
                        binding.llDustCollectionSettings.setVisibility(View.GONE);
                    }
                    AppContext.getProductService().setDeviceCleanSettings(CleanSettingParam.newBuilder().autoDustFrequency(0).build());
                }
            }
        });

        loadProgressDialog.addAnimatorListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                loadProgressDialog.dismiss();
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });

        binding.ivDustcolleCtingReturn.setOnClickListener(this);
        binding.btnDustImmediately.setOnClickListener(this);
        binding.llDustCollectionSettings1Time.setOnClickListener(this);
        binding.llDustCollectionSettings2Time.setOnClickListener(this);
        binding.llDustCollectionSettings3Time.setOnClickListener(this);

        String autoDust = settings.getAutoDust();//
        setDustCollectionFrequencySettings(autoDust);

        String dustSuction = settings.getDustSuction();
        if ("low".equals(dustSuction)) {
            binding.rgDustSuctionLow.setChecked(true);
        } else if ("middle".equals(dustSuction)) {
            binding.rgDustSuctionMedium.setChecked(true);
        } else if ("high".equals(dustSuction)) {
            binding.rgDustSuctionHigh.setChecked(true);
        }

        String dustTime = settings.getDustTime();
        if ("low".equals(dustTime)) {
            binding.rgDustTimeShort.setChecked(true);
        } else if ("middle".equals(dustTime)) {
            binding.rgDustTimeMedium.setChecked(true);
        } else if ("high".equals(dustTime)) {
            binding.rgDustTimeLong.setChecked(true);
        }
        binding.rgDustSuction.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                setDustSuction(checkedId);
            }
        });
        binding.rgDustTime.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                setDustTime(checkedId);
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (RomUtils.isFastClick()) {
            return;
        }
        int id = v.getId();
        if (id == R.id.iv_dustcolleCtingReturn) {
            Intent_utils.backIntent(this);
        } else if (id == R.id.btn_DustImmediately) {
            //集尘
            binding.btnDustImmediately.setClickable(false);
            loadProgressDialog.show();
            AppContext.getProductService().collectDust();
        } else if (id == R.id.ll_DustCollectionSettings_1_Time) {
            AppContext.getProductService().setDeviceCleanSettings(CleanSettingParam.newBuilder().autoDustFrequency(1).build());
            setDustCollectionFrequencySettings("1");
        } else if (id == R.id.ll_DustCollectionSettings_2_Time) {
            AppContext.getProductService().setDeviceCleanSettings(CleanSettingParam.newBuilder().autoDustFrequency(2).build());
            setDustCollectionFrequencySettings("2");
        } else if (id == R.id.ll_DustCollectionSettings_3_Time) {
            AppContext.getProductService().setDeviceCleanSettings(CleanSettingParam.newBuilder().autoDustFrequency(3).build());
            setDustCollectionFrequencySettings("3");
        }

    }

    @SuppressLint("LongLogTag")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        //获取dp：128
        switch (event.getType()) {
            case Event.MSG_ROBOT_STATE:
                LogUtils.i(" wwwwwwwwwwwwwwwwwwwwwwwwwwwwww ---2222------- ");
                binding.btnDustImmediately.setClickable(true);
                int state = AppContext.get().getCurrentDevice().getRobotStatus().getWorkState();
                if (state == RobotStatus.STATE_CHARGING) {
                    //充电中或充电完成
                    binding.tvRobotIsNotCharging.setVisibility(View.GONE);
                    binding.btnDustImmediately.setEnabled(true);
                } else if (state == RobotStatus.STATE_DUST_COLLECTION) {
                    LogUtils.i(" wwwwwwwwwwwwwwwwwwwwwwwwwwwwww ---11111------- ");
                    String mes = AppContext.get().getCurrentDevice().getRobotStatus().getMessage();
                    if (!singState.equals(mes)) {
                        singState = mes;
                        //集尘状态
                        judgeDustState(mes);
                    }
                } else {
                    binding.tvRobotIsNotCharging.setVisibility(View.VISIBLE);
                    binding.btnDustImmediately.setEnabled(false);
                }
                break;
            case Event.MESSAGE_TYPE_DUST_COLLECTION_NUM:
                //集尘次数
                int content = (int) event.getContent();
                if (frequency != content) {
                    frequency = content;
                    LogUtils.i(" 集尘次数------- " + content);
                    setDustCollectionFrequencySettings(content + "");
                }
                break;
        }
    }

    /**
     * 集尘吸力
     *
     * @param
     */
    private void setDustSuction(int checkedId) {
        String dustSuction = "";
        if (checkedId == R.id.rg_dustSuctionLow) {
            dustSuction = "low";
        } else if (checkedId == R.id.rg_dustSuctionMedium) {
            dustSuction = "middle";
        } else if (checkedId == R.id.rg_dustSuctionHigh) {
            dustSuction = "high";
        }
        LogUtils.i(" 集尘吸力------- " + dustSuction);
        AppContext.getProductService().setDeviceCleanSettings(CleanSettingParam.newBuilder().setDustSuction(dustSuction).build());
    }

    /**
     * 集尘时长
     *
     * @param
     */
    private void setDustTime(int checkedId) {
        String dustTime = "";
        if (checkedId == R.id.rg_dustTimeShort) {
            dustTime = "low";
        } else if (checkedId == R.id.rg_dustTimeMedium) {
            dustTime = "middle";
        } else if (checkedId == R.id.rg_dustTimeLong) {
            dustTime = "high";
        }
        LogUtils.i(" 集尘时长------- " + dustTime);
        AppContext.getProductService().setDeviceCleanSettings(CleanSettingParam.newBuilder().setDustTime(dustTime).build());
    }

    String singState = "0";

    /**
     * 判断当前集尘桶的状态
     */
    @SuppressLint("LongLogTag")
    private void judgeDustState(String mes) {
        if (loadProgressDialog != null) {
            loadProgressDialog.dismiss();
        }
        if (dialog != null) {
            dialog.dismiss();
        }
        //添加进入该界面标记
        if (mes.equals("14")) {
            dustCollectHintDialog(getString(R.string.Dust_full_reminder), getString(R.string.dust_bag_full));
        } else if (mes.equals("15")) {
            dustCollectHintDialog(getString(R.string.Dust_full_reminder), getString(R.string.no_dust_bags));
        } else if (mes.equals("19")) {
            dustCollectHintDialog(getString(R.string.Dust_full_reminder), getString(R.string.Frequent_dust));
        } else if (mes.equals("20")) {
            Log.i(TAG, " wwwwwwwwwwwwwwwwwwwwwwwwwwwwww ---33333333333333333333333------- ");
            dustCollectHintDialog(getString(R.string.Dust_full_reminder), getString(R.string.Finished_collecting_dust));
        } else if (mes.equals("21")) {
            dustCollectHintDialog(getString(R.string.Dust_collecting_duct_blocked), getString(R.string.dust_collector_blocked));
        }
    }

    @SuppressLint("LongLogTag")
    private void dustCollectHintDialog(String dialogTitle, String content) {
        Log.i(TAG, " wwwwwwwwwwwwwwwwwwwwwwwwwwwwww ---4444444444444444444444------- ");
        dialog = new Dialog(DustCollectingBarrelActivity.this);
        dialog.setContentView(R.layout.hint_dialog);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.setCanceledOnTouchOutside(false);

        TextView mBtnCenteredConfirm = dialog.findViewById(R.id.btn_hintConfirm);
        TextView mTvDialogTitle = dialog.findViewById(R.id.tv_dialogHintTitle);
        TextView mTvDialogContent = dialog.findViewById(R.id.tv_hint_content);
        mTvDialogTitle.setText(dialogTitle);
        mTvDialogContent.setText(content);
        mBtnCenteredConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
        mBtnCenteredConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                return true;
            }
        });
        dialog.show();
        Log.i(TAG, " wwwwwwwwwwwwwwwwwwwwwwwwwwwwww ---555555555555555555555555------- ");
    }

    private void setDustCollectionFrequencySettings(String frequency) {
        if ("1".equals(frequency)) {
            binding.tvDustCollectionSettingsOneTime.setTextColor(ContextCompat.getColor(this, R.color.white));
            binding.tvDustCollectionSettingsOneTimeExplain.setTextColor(ContextCompat.getColor(this, R.color.background_color));

            binding.tvDustCollectionSettingsTwoTime.setTextColor(ContextCompat.getColor(this, R.color.textview_color2));
            binding.tvDustCollectionSettingsTwoTimeExplain.setTextColor(ContextCompat.getColor(this, R.color.textview_color3));

            binding.tvDustCollectionSettingsThreeTime.setTextColor(ContextCompat.getColor(this, R.color.textview_color2));
            binding.tvDustCollectionSettingsThreeTimeExplain.setTextColor(ContextCompat.getColor(this, R.color.textview_color3));

            binding.llDustCollectionSettings1Time.setBackgroundResource(R.mipmap.button_bg_icon);//选中
            binding.llDustCollectionSettings2Time.setBackgroundResource(R.mipmap.button_bg_icon_2);
            binding.llDustCollectionSettings3Time.setBackgroundResource(R.mipmap.button_bg_icon_2);
        } else if ("2".equals(frequency)) {
            binding.tvDustCollectionSettingsOneTime.setTextColor(ContextCompat.getColor(this, R.color.textview_color2));
            binding.tvDustCollectionSettingsOneTimeExplain.setTextColor(ContextCompat.getColor(this, R.color.textview_color3));

            binding.tvDustCollectionSettingsTwoTime.setTextColor(ContextCompat.getColor(this, R.color.white));
            binding.tvDustCollectionSettingsTwoTimeExplain.setTextColor(ContextCompat.getColor(this, R.color.background_color));

            binding.tvDustCollectionSettingsThreeTime.setTextColor(ContextCompat.getColor(this, R.color.textview_color2));
            binding.tvDustCollectionSettingsThreeTimeExplain.setTextColor(ContextCompat.getColor(this, R.color.textview_color3));
            binding.llDustCollectionSettings1Time.setBackgroundResource(R.mipmap.button_bg_icon_2);
            binding.llDustCollectionSettings2Time.setBackgroundResource(R.mipmap.button_bg_icon);//选中
            binding.llDustCollectionSettings3Time.setBackgroundResource(R.mipmap.button_bg_icon_2);
        } else if ("3".equals(frequency)) {
            binding.tvDustCollectionSettingsOneTime.setTextColor(ContextCompat.getColor(this, R.color.textview_color2));
            binding.tvDustCollectionSettingsOneTimeExplain.setTextColor(ContextCompat.getColor(this, R.color.textview_color3));

            binding.tvDustCollectionSettingsTwoTime.setTextColor(ContextCompat.getColor(this, R.color.textview_color2));
            binding.tvDustCollectionSettingsTwoTimeExplain.setTextColor(ContextCompat.getColor(this, R.color.textview_color3));

            binding.tvDustCollectionSettingsThreeTime.setTextColor(ContextCompat.getColor(this, R.color.white));
            binding.tvDustCollectionSettingsThreeTimeExplain.setTextColor(ContextCompat.getColor(this, R.color.background_color));
            binding.llDustCollectionSettings1Time.setBackgroundResource(R.mipmap.button_bg_icon_2);
            binding.llDustCollectionSettings2Time.setBackgroundResource(R.mipmap.button_bg_icon_2);
            binding.llDustCollectionSettings3Time.setBackgroundResource(R.mipmap.button_bg_icon);//选中
        }

    }


    @SuppressLint("RestrictedApi")
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            //do something.
            if (dialog != null) {
                if (!dialog.isShowing()) {
                    return super.dispatchKeyEvent(event);
                } else {
                    return true;
                }
            } else {
                return super.dispatchKeyEvent(event);
            }
        }
        return super.dispatchKeyEvent(event);
    }

    /**
     * 底部弹框
     */
//    private void showDialog() {
//        Log.i(TAG, "----------");
//        sheetDialog = new BottomSheetDialog(DustCollectingBarrelActivity.this);
//        View view = LayoutInflater.from(this).inflate(R.layout.layout_dust_set, null);
//        RadioGroup mDustRG = view.findViewById(R.id.dust_radioGroup);
//        RadioButton mRBOneDust = view.findViewById(R.id.rb_OneDust);
//        RadioButton mRBTwoDust = view.findViewById(R.id.rb_TwoDust);
//        RadioButton mRBthreeDust = view.findViewById(R.id.rb_threeDust);
//        mDustRG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(RadioGroup group, int checkedId) {
//                switch (checkedId) {
//                    case R.id.rb_OneDust:
//                        Constants.dustTimes = mRBOneDust.getText().toString().trim();
//                        dustNum = 1;
//                        break;
//                    case R.id.rb_TwoDust:
//                        Constants.dustTimes = mRBTwoDust.getText().toString().trim();
//                        dustNum = 2;
//                        break;
//                    case R.id.rb_threeDust:
//                        Constants.dustTimes = mRBthreeDust.getText().toString().trim();
//                        dustNum = 3;
//                        break;
//                }
////                mTvDustCollectBarrel.setText(Constants.dustTimes);
//                TuyaConnector.sendOrderConnectorString(Constants.DP_ID_SET_DUST_COLLECTION_NUM, dustNum + "");
//                sheetDialog.dismiss();
//            }
//        });
//
//        sheetDialog.setContentView(view);
//        //设置透明背景
//        sheetDialog.getWindow().findViewById(R.id.design_bottom_sheet)
//                .setBackgroundResource(android.R.color.transparent);
//        sheetDialog.show();
//    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
